package com.example.demo.controller.front;

import com.example.demo.dao.Admin;
import com.example.demo.dao.Goods;
import com.example.demo.dao.User;
import com.example.demo.service.GoodsService;
import com.example.demo.service.UserService;
import com.example.demo.util.JavaMailUtils;
import com.example.demo.util.Msg;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/users")
public class login {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;

//    //登录页面
//    @RequestMapping("/show ")
//    public String show(HttpSession session){
//        session.invalidate();
//        return "index";
//    }
//用户登录
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String userlogin( HttpServletRequest request, Model model) {
        String username =  request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.login(username, password);
        if (user != null) {
            //保存用户
            HttpSession session = request.getSession();
            session.setAttribute("id", user.getUserid());
            String id = session.getAttribute("id").toString();
            session.setAttribute("session_user", user);
            //显示商品
            List<Goods> goods = goodsService.goods();
            model.addAttribute("goods",goods);
            return "main";
        }
        return "index";//密码输入错误
    }

    @PostMapping(value = "/Register")
    public String showRegister(){
        return "Register";
    }


//用户注册
@PostMapping("/regist")
@ResponseBody
    public Msg Regist(User user1, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
          String email =user1.getEmail();
            String username = user1.getUsername();
           String password = user1.getPassword();
          String password2 =user1.getPassword2();
          System.out.println(username);
            String code = user1.getCode();
            if(!password.equals(password2)){
                return Msg.fail("两次输入的密码不一致");
            }else{
            User user = userService.login(username,password);
            User user2 = userService.findUserByEmail(email);
                    session=request.getSession(false);
            String sessionEmail =(String)session.getAttribute("email");
            String sessionCode = (String) session.getAttribute("code");
            if(user == null && user2==null && sessionEmail.equals(email)&& sessionCode.equals(code)) {
                //时间
                Date time = new Date();
                java.sql.Date date = new java.sql.Date(time.getTime());
                User newUser = new User(username, password, email, date);
                int update = userService.zhuce(newUser);
                if (update > 0) {
                    return Msg.success("注册成功");
                } else {
                    return Msg.fail("注册失败");
                }
            }else{
                return Msg.fail("用户已存在");
            }


        }
    }
    //邮箱验证码
    @PostMapping(value = "/registerCode")
    public void registerCode(HttpServletResponse response,HttpServletRequest request,HttpSession session,String email) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Random rm = new Random();
        String code ="";
        for(int i = 0;i<4;i++) {
            int num = rm.nextInt(26) + 65;
            code += (char) num;
        }
        JavaMailUtils.sendMail(email,code);
        session=request.getSession(true);
        session.setAttribute("code",code);
        session.setAttribute("email" ,email);
        session.setMaxInactiveInterval(60);

    }


    //跳转主页
    @RequestMapping(value = "/main")
    public String returnmain(HttpSession session,Model model,HttpServletRequest request){
        Integer userid = (Integer) session.getAttribute("id");
        //显示商品
        HttpSession session1 = request.getSession();
        session1.setAttribute("id",userid);
        List<Goods> goods = goodsService.goods();
        model.addAttribute("goods",goods);
        return "main";
    }


    //忘记密码页面跳转
    @RequestMapping(value = "/forget")
    public String goforget(){
        return "forget";
    }

    //忘记密码邮箱验证
    @PostMapping(value = "/setEmail")
    public void setEmail(HttpServletRequest request,HttpServletResponse response,String email,HttpSession session) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Random rm = new Random();
        String code="";
        for(int i=0;i<4;i++){
            int num = rm.nextInt(26)+65;
            code+=(char) num;
        }
        JavaMailUtils.findPasswordMail(email,code);
        session =request.getSession(true);
        session.setAttribute("usercode",code);
        session.setMaxInactiveInterval(60);
    }


    //找回密码
    @PostMapping(value = "/getpassword")
    @ResponseBody
    public Msg getPassword(HttpServletRequest request,HttpServletResponse response,String email,String password,String password2,String code,HttpSession session) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String code1 =(String) session.getAttribute("usercode");
        User user = userService.findUserByEmail(email);
        if(user !=null &&code1.equals(code)){
            user.setPassword(password);
            userService.editUser(user);
            return Msg.success("找回密码成功");
        }
        return Msg.fail("该账户不存在或验证码错误");
    }
    }


